package com.hmall.api.config;

import feign.Logger;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.context.annotation.Bean;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Enumeration;

public class DefaultFeignConfig{
    @Bean
    public Logger.Level feignLoggerLevel(){
        return Logger.Level.BASIC;
    }
    /**
     * 创建OpenFeign拦截器->将所有请求头信息再封装，传给要调用的服务
     */
    @Bean
    public RequestInterceptor userInfoRequestInterceptor(){
        return requestTemplate -> {
            //1.获取网关传过来的所有请求头(获取主线程的上下文对象)
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = requestAttributes.getRequest();
            //2.在循环所有请求头，再封装一次请求头，传递要调用的微服务
            Enumeration<String> headerNames = request.getHeaderNames();
            while (headerNames.hasMoreElements()){
                String key = headerNames.nextElement();
                String value = request.getHeader(key);

                //content-length
                if (key.equalsIgnoreCase("content-length")){
                    continue;
                }
                //再封装一次请求头，传递要调用的微服务
                requestTemplate.header(key,value);
            }
        };

    }
}
